package saucaca.CustomView;

import java.util.ArrayList;

import org.json.JSONException;

import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.AlbumObject;
import saucaca.Object.SearchObject;
import saucaca.Object.SingerObject;
import saucaca.Object.SongObject;
import saucaca.Util.CMD;
import saucaca.Util.TagName;
import saucaca.fragment.AlbumDetailFargment;
import saucaca.fragment.ArtistDetailFragment;
import lemon.kenhnhacvn.BaseEngine;
import lemon.kenhnhacvn.MainActivity;
import lemon.kenhnhacvn.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class CustomActionbar extends RelativeLayout {
	private LayoutInflater layoutInflater;
	RelativeLayout mActionLayout;
	ImageView imgLogo, imgSearchicon, imgHomeicon;
	TextView txtMenutitle;
	AutoCompleteTextView completeTextView;
	Context context;
	GetSearch getSearch;
	boolean isSearch = false,isHome;
	ArrayAdapter<SearchObject> adapter;
	ArrayList<SongObject> listSong = null;
	ArrayList<AlbumObject> listALBUM = null;
	ArrayList<SongObject> listVIDEO = null;
	ArrayList<SingerObject> listSinger = null;
	int singerSize = 0;
	int songSize = 0;
	int albumSize = 0;
	int videoSize = 0;
	public CustomActionbar(final Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mActionLayout = (RelativeLayout) layoutInflater.inflate(R.layout.actionbar_menu, null);
		addView(mActionLayout);

		listSong = new ArrayList<SongObject>();
		listALBUM = new ArrayList<AlbumObject>();
		listVIDEO = new ArrayList<SongObject>();
		listSinger = new ArrayList<SingerObject>();
		
		imgLogo = (ImageView) mActionLayout.findViewById(R.id.home_imgLogo);
		imgHomeicon = (ImageView) mActionLayout.findViewById(R.id.menu_top_navigation);
		imgSearchicon = (ImageView) mActionLayout.findViewById(R.id.menu_top_search);
		imgSearchicon.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				isSearch = !isSearch;
				toggleSearchview();
			}
		});
		
		txtMenutitle = (TextView) mActionLayout.findViewById(R.id.menu_top_text_title);
		completeTextView = (AutoCompleteTextView) mActionLayout.findViewById(R.id.search_home);
		completeTextView.addTextChangedListener(new TextWatcher() {

			@SuppressWarnings("unused")
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.length()>1){
					if (getSearch == null) {
						getSearch = new GetSearch();
						getSearch.execute(s.toString());
					} else {
						if (getSearch.getStatus() == AsyncTask.Status.RUNNING) {
							getSearch.cancel(true);
							getSearch = new GetSearch();
							getSearch.execute(s.toString());
						} else {
							getSearch = new GetSearch();
							getSearch.execute(s.toString());
						}
					}
					isSearch=!isSearch;
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		completeTextView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//				isSearch = !isSearch;
//				imgLogo.setVisibility(View.VISIBLE);
//				completeTextView.setVisibility(View.GONE);
//				completeTextView.setText("");
//				imgSearchicon.setImageResource(R.drawable.search_icon);
//				completeTextView.setText("");
//				TagName.showToastShort(context, "code chọn item search!!!");
				completeTextView.setText("");
				TagName.showLogError("Search", "index: "+position);
				if(position<=singerSize-1){
					((MainActivity)context).switchContent(ArtistDetailFragment.class.getName(), listSinger.get(position));
				}else if (position<=singerSize-1+albumSize) {
					((MainActivity) context).switchContent(AlbumDetailFargment.class.getName(), listALBUM.get(position-singerSize));
				}else if (position<=singerSize-1+albumSize+videoSize) {
					BaseEngine.setVideoclick(context, listVIDEO.get(position-singerSize-albumSize));
				}else{
					new songDetailsServices().execute(listSong.get(position-singerSize-albumSize-videoSize).getSONG_ID());
				}
				toggleSearchview();
				isSearch=true;
			}
		});
	}
	class songDetailsServices extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.idDetais(CMD.CMD_SONG_DETAIL, params[0]);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null)
				try {
					ArrayList<SongObject> listsongs = JsonReader.readSongdetail(result);
					if (listsongs != null	&& listsongs.size()>0){
						SongObject songObject=listsongs.get(0);
						try {
							((MainActivity) context).mPlaylistMgr.add(songObject);
							((MainActivity) context).play(((MainActivity) context).mPlaylistMgr.getArrayList().size()-1);
						} catch (Exception e) {
							ArrayList<SongObject> lists = new ArrayList<SongObject>();
							lists.add(songObject);
							((MainActivity) context).SendPlaylistAndplay(lists, 0);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
		}
	}
	public void toggleSearchview(){
		if (isSearch) {
			imgLogo.setVisibility(View.GONE);
			txtMenutitle.setVisibility(View.GONE);
			completeTextView.setVisibility(View.VISIBLE);
			completeTextView.requestFocus();
			imgSearchicon.setImageResource(R.drawable.ic_action_remove);
		} else {
			if(isHome){
				imgLogo.setVisibility(View.VISIBLE);
			}else txtMenutitle.setVisibility(View.VISIBLE);
			completeTextView.setVisibility(View.GONE);
			completeTextView.setText("");
			imgSearchicon.setImageResource(R.drawable.search_icon);
		}
	}
	public void setTitle(String title) {
		txtMenutitle.setText(title);
	}
	
	public void setMenu(CharSequence title, boolean isHome, boolean isMenu) {
		this.isHome=isHome;
		txtMenutitle.setText(title);
		setActionbar(isHome,isMenu);
		isSearch=false;
		toggleSearchview();
	}
	
	public void setMenu(int resid, boolean isHome, boolean isMenu) {
		this.isHome=isHome;
		txtMenutitle.setText(resid);
		setActionbar(isHome,isMenu);
		isSearch=false;
		toggleSearchview();
	}
	private void setActionbar(boolean isHome, boolean isMenu) {
		if (isHome) {
			imgLogo.setVisibility(View.VISIBLE);
			txtMenutitle.setVisibility(View.GONE);
			imgHomeicon.setImageResource(R.drawable.menu_left);
			imgHomeicon.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					((MainActivity) context).getSlidingMenu().showMenu();
				}
			});
		} else {
			imgLogo.setVisibility(View.GONE);
			txtMenutitle.setVisibility(View.VISIBLE);
			if (isMenu) {
				imgHomeicon.setImageResource(R.drawable.menu_left);
				imgHomeicon.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						((MainActivity) context).getSlidingMenu().showMenu();
					}
				});
			} else {
				imgHomeicon.setImageResource(R.drawable.back_icon_ht);
				imgHomeicon.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						((MainActivity) context).showprevousFragment();
					}
				});
			}
		}
	}

	class GetSearch extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.search(params[0]);
			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null) {
				listSong.clear();
				listALBUM.clear();
				listVIDEO.clear();
				listSinger.clear();
				ArrayList<SongObject> listSongJson = null;
				ArrayList<AlbumObject> listALBUMJson = null;
				ArrayList<SongObject> listVIDEOJson = null;
				ArrayList<SingerObject> listSingerJson = null;
				try {
					listSongJson = JsonReader.searchSong(result);
					listALBUMJson = JsonReader.searchAlbum(result);
					listVIDEOJson = JsonReader.searchVideo(result);
					listSingerJson = JsonReader.searchSinger(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}

			if (listSingerJson != null&&listSingerJson.size()>0){
				singerSize = listSingerJson.size();
				for (int i = 0; i < singerSize; i++) {
					listSinger.add(listSingerJson.get(i));
				}
			}else singerSize=0;
			if (listALBUMJson != null&&listALBUMJson.size()>0){
				albumSize = listALBUMJson.size();
				for (int i = 0; i < albumSize; i++) {
					listALBUM.add(listALBUMJson.get(i));
				}
			}else albumSize=0;
			if (listVIDEOJson != null&&listVIDEOJson.size()>0){
				videoSize = listVIDEOJson.size();
				for (int i = 0; i < videoSize; i++) {
					listVIDEO.add(listVIDEOJson.get(i));
				}
			}else videoSize=0;
			if (listSongJson != null&&listSongJson.size()>0){
				songSize = listSongJson.size();
				for (int i = 0; i < songSize; i++) {
					listSong.add(listSongJson.get(i));
				}
			}else songSize=0;
			
			SearchObject[] people = new SearchObject[singerSize + albumSize + videoSize + songSize];
			for (int i = 0; i < singerSize; i++) {
				people[i] = new SearchObject(R.drawable.bl_avatar1, listSinger.get(i).getTXNAME());
			}
			for (int i = 0; i < albumSize; i++) {
				people[i + singerSize] = new SearchObject(R.drawable.cn_album, listALBUM.get(i).getTXNAME());
			}
			for (int i = 0; i < videoSize; i++) {
				people[i + singerSize + albumSize] = new SearchObject(R.drawable.cn_video, listVIDEO.get(i).getTXNAME());
			}
			for (int i = 0; i < songSize; i++) {
				people[i + singerSize + albumSize + videoSize] = new SearchObject(R.drawable.cn_baihat, listSong.get(i).getTXNAME());
			}
			adapter = new FilteredArrayAdapter<SearchObject>(context, R.layout.item_search, people) {
				@Override
				public View getView(int position, View convertView, ViewGroup parent) {
					if (convertView == null) {

						LayoutInflater l = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
						convertView = (View) l.inflate(R.layout.item_search, parent, false);
					}
					SearchObject p = getItem(position);
					if (p != null) {
						ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
						imageView.setImageResource(p.avatar);
						((TextView) convertView.findViewById(R.id.textView)).setText(p.Name);
					}
					return convertView;
				}

				@SuppressLint("DefaultLocale")
				@Override
				protected boolean keepObject(SearchObject obj, String mask) {
					mask = mask.toLowerCase();
					return obj.Name.toLowerCase().startsWith(mask);
				}
			};
			completeTextView.setAdapter(adapter);
			completeTextView.showDropDown();
			isSearch=!isSearch;
		}
		}
	}
}
